package com.itheima.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @version V1.0
 * @author: yongjichu
 * @date: 2020/2/8 15:47
 * @description:
 */
@Component
public class SpringSecurityUserService implements UserDetailsService {
    @Reference
    UserService userService;

    /**
     * 根据用户名获取用户的密码，角色还用权限
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user=userService.findByUsername(username);
        if(user==null){
            return null;
        }
        //将用户的所有的权限都放在这个集合里面
        List<SimpleGrantedAuthority> authorities=new ArrayList<>();
        //1.获取集合的角色
        Set<Role> roles = user.getRoles();
        //2.遍历roles
        for (Role role : roles) {
            //3.获取role里面的权限
            Set<Permission> permissions = role.getPermissions();
            //4.循环permissions
            for (Permission permission : permissions) {
                //将权限设置到集合里面,这里的keyword就是权限的名称
                authorities.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }
        //将最终的结果返回(因为参数要求就要返回用户名，密码还有用户的权限的集合)
        return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),authorities);
    }
}
